const gulp = require('gulp');
const sass = require('gulp-sass');
const cleanCSS = require('gulp-clean-css');
const browserSync = require('browser-sync').create();
const proxy = require('http-proxy-middleware');
const rename = require('gulp-rename');
const changed = require('gulp-changed');
const uglify = require('gulp-uglify');
const concat = require('gulp-concat');
const babel = require('gulp-babel');
const gulpif = require('gulp-if');
const scp = require('gulp-scp2');
const eslint = require('gulp-eslint');
const autoprefixer = require('gulp-autoprefixer');
const order = require('gulp-order');
const browserify = require('gulp-browserify');

const config = require('./config');

const shouldUglify = process.env.npm_lifecycle_script === 'gulp build';

gulp.task('js:ace', () => {
  /* eslint-disable no-useless-escape */
  return gulp.src(['./app/assets/js/ace/*.js', '!./app/assets/js/ace/ace.auto-padding.js', '!./app/assets/js/ace/ace.auto-container.js'])
    .pipe(order([
      'elements.scroller.js',
      'elements.colorpicker.js',
      'elements.fileinput.js',
      'elements.typeahead.js',
      'elements.wysiwyg.js',
      'elements.spinner.js',
      'elements.treeview.js',
      'elements.wizard.js',
      'elements.aside.js',
      'ace.js',
      'ace.ajax-content.js',
      'ace.touch-drag.js',
      'ace.sidebar.js',
      'ace.sidebar-scroll-1.js',
      'ace.submenu-hover.js',
      'ace.widget-box.js',
      'ace.settings.js',
      'ace.settings-rtl.js',
      'ace.settings-skin.js',
      'ace.widget-on-reload.js',
      'ace.searchbox-autocomplete.js',
      'ace.auto-padding.js'
    ]))
    .pipe(babel())
    .pipe(concat('ace.js'))
    .pipe(gulp.dest('./app/assets/js/'))
    .pipe(uglify())
    .pipe(concat('ace.min.js'))
    .pipe(gulp.dest('./app/assets/js/'))
    .pipe(browserSync.stream());
});

gulp.task('scss', () => {
  /* eslint-disable no-useless-escape */
  return gulp.src(['./app/public/stylesheets/**/*.scss', './app/public/stylesheets/styles/**/*.scss', '!./app/public/stylesheets/**/\_*.sass'])
    .pipe(sass().on('error', sass.logError))
    .pipe(autoprefixer({
      browsers: ['last 20 versions'],
      cascade: false
    }))
    .pipe(cleanCSS({ compatibility: 'ie8' }))
    .pipe(rename({ suffix: '.min' }))
    .pipe(gulp.dest('./app/public/stylesheets'))
    .pipe(browserSync.stream());
});

gulp.task('js:scripts', () => {
  return gulp.src(['./app/public/javascripts/scripts/**/*.js', '!./app/public/javascripts/scripts/**/*.min.js'])
    .pipe(changed('./app/public/javascripts/scripts', { extension: '.min.js' }))
    .pipe(babel())
    .pipe(uglify())
    .pipe(rename({ extname: '.min.js' }))
    .pipe(gulp.dest('./app/public/javascripts/scripts'))
    .pipe(browserSync.stream());
});

gulp.task('js:utils', () => {
  return gulp.src(['./app/public/javascripts/utils/index.js'])
    .pipe(browserify({ transform: ['babelify'] }))
    .on('error', console.log)
    .pipe(gulpif(shouldUglify, uglify()))
    .pipe(concat('utils.js'))
    .pipe(rename({ extname: '.min.js' }))
    .pipe(gulp.dest('./app/public/javascripts/utils'))
    .pipe(browserSync.stream());
});

gulp.task('lint:utils', () => {
  return gulp.src(['./app/public/javascripts/utils/**/*.js', '!./app/public/javascripts/utils/**/*.min.js'])
    .pipe(eslint())
    .pipe(eslint.format())
    .pipe(eslint.failAfterError());
});

gulp.task('js', ['js:scripts', 'js:utils'], () => {});

gulp.task('reload', () => {
  browserSync.reload();
});

gulp.task('dev', ['js', 'scss'], () => {
  console.log(`[${new Date()}]: ready to develop!`);
  const domains = {
    // huashengke: 'http://carnation.51vip.biz:35675/',
    huashengke2: 'http://16e956529h.iask.in:32135/',
    // test: 'http://127.0.0.1:8080/travel.manage.vc/',
    test: 'http://47.95.215.100:8080',
    production: 'http://sys.aiwanlx.com/'
  };
  browserSync.init({
    server: {
      baseDir: './app',
      directory: true
    },
    port: '5000',
    startPath: `./views/login.html`,
    middleware: [
      proxy('**/*.do', {
        target: domains.test,
        changeOrigin: true
      })
    ]
  });
  gulp.watch(['./app/public/stylesheets/**/*.scss', './app/public/stylesheets/styles/**/*.scss', '!./app/public/stylesheets/**/\_*.sass'], ['scss']);
  gulp.watch(['./app/public/javascripts/utils/**/*.js', '!./app/public/javascripts/utils/**/*.min.js'], ['js:utils', 'lint:utils']);
  gulp.watch(['./app/public/javascripts/scripts/**/*.js', '!./app/public/javascripts/scripts/**/*.min.js'], ['js:scripts']);
});

gulp.task('build', ['js', 'scss'], () => {
  console.log(`[${new Date()}]: Finish building!`);
});

gulp.task('deployToTestServer', () => {
  return gulp.src(['./app/**/*.*'])
    .pipe(scp({
      host: config.deployForTestServer.hostname,
      username: config.deployForTestServer.username,
      password: config.deployForTestServer.password,
      dest: config.deployForTestServer.dest
    }));
});

gulp.task('deployToProductionServer', () => {
  return gulp.src(['./app/**/*.*'])
    .pipe(scp({
      host: config.deployForProductionServer.hostname,
      username: config.deployForProductionServer.username,
      password: config.deployForProductionServer.password,
      dest: config.deployForProductionServer.dest
    }));
});

gulp.task('default', ['dev'], () => {});
